//
//  CXHttpMgr.swift
//  CXRobotServer
//
//  Created by ezreal on 2019/4/24.
//

import Foundation
import SwiftyJSON

let BSPHP_MUTUALKEY_PUBGM = "2c07f453e88a7a300804acf357da13cf"
let BSPHP_HOST_PUBGM = "http://148.163.166.57/AppEn.php?appid=10000&m=e2044a44b7c9fa92992424b2543eb8fb"
var BSPHPSESSL_PUBGM:String? = nil

class CXHttpMgr: NSObject {

    static let shared = CXHttpMgr()
    
    private func sendSynchronousRequest(url:String,body:Data?) ->Data?{
        
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "POST"
        request.httpBody = body
        let semaphore = DispatchSemaphore(value: 0)
        var resultData:Data? = nil
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            resultData = data
            semaphore.signal()
        }
        task.resume()
        
        semaphore.wait()
        
        return resultData
    }
    
    public func getBSphpSeSsL(appId:UInt32){
        
        var param = Dictionary<String, String>()
        param["api"] = "BSphpSeSsL.in"
        param["date"] = CXHelper.getSystemDate()
        param["md5"] = ""
        
        var BSPHP_HOST:String
        
        if(appId == 10000){
            param["mutualkey"] = BSPHP_MUTUALKEY_PUBGM
            BSPHP_HOST = BSPHP_HOST_PUBGM
        }else{
            param["mutualkey"] = BSPHP_MUTUALKEY_PUBGM
            BSPHP_HOST = BSPHP_HOST_PUBGM
        }
        
        let data = self.sendSynchronousRequest(url: BSPHP_HOST, body: CXHelper.getParamData(param: param))
        
        if(data != nil)
        {
            do{
                let json = try JSON(data: data!)
                if let token = json["response"]["data"].string
                {
                    if(appId == 10000){
                        BSPHPSESSL_PUBGM = token
                    }else{
                        BSPHPSESSL_PUBGM = token
                    }
                    log.debug("\(appId) getBSphpSeSsL:\(token)")
                }
                else
                {
                    log.error("获取getBSphpSeSsL失败appID:\(appId)")
                    exit(0)
                }
            }catch{
                log.error("获取getBSphpSeSsL失败appID:\(appId)")
                exit(0)
            }
        }
        else
        {
            log.error("获取getBSphpSeSsL失败appID:\(appId)")
            exit(0)
        }
    }
    
    func login(appId:UInt32,code:String,deviceId:String) -> NSError {
        
        var param = Dictionary<String, String>()
        param["api"] = "login.ic"
        param["date"] = CXHelper.getSystemDate()
        param["md5"] = ""
        param["icid"] = code
        param["icpwd"] = ""
        param["key"] = deviceId
        param["maxoror"] = deviceId
        
        var BSPHP_HOST:String
        if(appId == 10000){
            param["BSphpSeSsL"] = BSPHPSESSL_PUBGM
            param["mutualkey"] = BSPHP_MUTUALKEY_PUBGM
            BSPHP_HOST = BSPHP_HOST_PUBGM
        }else{
            param["BSphpSeSsL"] = BSPHPSESSL_PUBGM
            param["mutualkey"] = BSPHP_MUTUALKEY_PUBGM
            BSPHP_HOST = BSPHP_HOST_PUBGM
        }
        
        var resultError:NSError = NSError(domain: "com.xmzd.request.validation", code: -4, userInfo: [NSLocalizedDescriptionKey:"其他错误"])
        
        let data = self.sendSynchronousRequest(url: BSPHP_HOST, body: CXHelper.getParamData(param: param))
        
        if (data != nil)
        {
            do{
                let json = try JSON(data: data!)
                if let strData = json["response"]["data"].string
                {
                    if(strData.contains("01|1081|"))
                    {
                        
                        let startIndex = strData.index(strData.endIndex, offsetBy: -24)
                        let endIndex = strData.index(strData.endIndex, offsetBy: -5)
                        let strDate = strData[startIndex..<endIndex]
                        //登录成功
                        log.info("激活成功:appId:\(appId) code:\(code) deviceId:\(deviceId) 到期时间:\(strDate)")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: 0, userInfo: [NSLocalizedDescriptionKey:"激活成功:到期时间\(strDate)"])
                    }
                    else if(strData.contains("5035"))
                    {
                        log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("激活码已绑定其他设备")")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: -1, userInfo: [NSLocalizedDescriptionKey:"激活失败:激活码已绑定其他设备"])
                    }
                    else if(strData.contains("你的使用期已到,请购卡在使用"))
                    {
                        log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("激活码已到期")")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: -2, userInfo: [NSLocalizedDescriptionKey:"激活失败:激活码已到期"])
                    }
                    else if(strData.contains("你的使用期已到,请购卡在使用"))
                    {
                        log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("激活码已到期")")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: -3, userInfo: [NSLocalizedDescriptionKey:"激活失败:激活码已到期"])
                    }
                    else if(strData.contains("激活码不存在"))
                    {
                        log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("激活码不存在")")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: -4, userInfo: [NSLocalizedDescriptionKey:"激活失败:激活码不存在"])
                    }
                    else if(strData.contains("激活码或者验证串已经被冻结,无法继续"))
                    {
                        log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("激活码或者验证串已经被冻结,无法继续")")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: -5, userInfo: [NSLocalizedDescriptionKey:"激活码或者验证串已经被冻结,无法继续"])
                    }
                    else
                    {
                        log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("其他错误") data:\(strData)")
                        resultError = NSError(domain: "com.xmzd.request.validation", code: -6, userInfo: [NSLocalizedDescriptionKey:"激活失败:\(strData)"])
                    }
                }
                else
                {
                    log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("data字段错误")")
                    resultError = NSError(domain: "com.xmzd.request.validation", code: -4, userInfo: [NSLocalizedDescriptionKey:"激活失败:其他错误"])
                }
            }catch{
                log.error("激活失败:appId:\(appId) code:\(code) deviceId:\(deviceId) desc:\("捕获到异常") error:\(error)")
                resultError = NSError(domain: "com.xmzd.request.validation", code: -3, userInfo: [NSLocalizedDescriptionKey:"激活失败:其他错误"])
                exit(0)
            }
        }
        return resultError
    }
}
